package com.tanhua.bg.login.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;

import com.tanhua.bg.login.service.LoginService;
import com.tanhua.bg.login.vo.LoginVo;
import com.tanhua.common.utils.NoAuthorization;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.time.Duration;
import java.util.Map;

@RestController
@RequestMapping("/system/users")
@Slf4j
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    //private final static Logger logger = LoggerFactory.getLogger(LoginController.class);

    /**
     * 后台登陆时 图片验证码 生成
     */
    @GetMapping("verification")
    @NoAuthorization
    public void showValidateCodePic(@RequestParam String uuid, HttpServletRequest request, HttpServletResponse res) throws IOException {
        res.setDateHeader("Expires",0);
        res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        res.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        res.setHeader("Pragma", "no-cache");
        res.setContentType("image/jpeg");
        // 设置图片验证码的大小宽度
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(299, 97, 4, 1);
        /*String code = lineCaptcha.getCode();

        //记录日志
        log.info("uuid={},code={}",uuid,code);
        System.out.println(code);
        // 调用service进行保存验证码
        loginService.saveCode(uuid,code);
        try {
            lineCaptcha.write(res.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        BufferedImage image = captcha.getImage();
        // 把验证码存入redis中
        String code = captcha.getCode();
        redisTemplate.opsForValue().set(uuid, code, Duration.ofMinutes(5));
        ImageIO.write(image, "JPEG", res.getOutputStream());

    }

    /***
     * 用户登录
     * @param param
     * @return
     */
    @PostMapping("login")
    @NoAuthorization
    public ResponseEntity <Map>login(@RequestBody Map<String,String> param){
        // 用户登录生成的token需要用map集合
        Map<String,String> result = loginService.login(param);
       try{ if (result != null) {
            return ResponseEntity.ok(result);
        }
    } catch (Exception e) {
        log.error("登录失败!");
    }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}

    /**
     * 用户基本信息
     * @return
     */
    @PostMapping("profile")
    public ResponseEntity<LoginVo> QueryUserProfile(@RequestHeader("Authorization") String token){
        // 调用service 进行信息封装
        LoginVo loginVo =null;
        try {
            loginVo = loginService.QueryUserProfile(token);
            if (loginVo !=null){
                return ResponseEntity.ok(loginVo);
            }
        } catch (Exception e) {
           log.error("用户校验失败，loginVo = " +loginVo,e);
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

   /* @PostMapping("/profile")
    public ResponseEntity profile(){
        Login admin = LoginThreadLocal.get();
        LoginVo vo = new LoginVo();
        BeanUtils.copyProperties(admin,vo);
        return ResponseEntity.ok(vo);
    }*/

    /**
     * 用户登出
     * @param token
     * @return
     */
    @PostMapping("/logout")
    @NoAuthorization
    public ResponseEntity logout(@RequestHeader("Authorization") String token){
        token =  token.replace("Bearer ", "");
        // 记录退出时间
        log.info(token);
        return loginService.logout(token);
    }

}
